<!-- src/components/AssignmentList.vue -->
<template>
  <div style="width:100vw;display:flex;justify-content: center;background:#F9F9F9">
    <div class="container" style="width:75vw">
      <!-- 导航栏 -->
      <AssignmentNavBar :homeworkId="homeworkId" :semesterId="semesterId" />

      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">
        <p>{{ errorMessage }}</p>
      </div>

      <!-- 筛选条件区域 -->
      <div class="filter-section">
        <!-- 批阅状态（单选） -->
        <div class="filter-options">
          <p>批阅状态：</p>
          <label>
            <input type="radio" v-model="filters.evaluationStatus" value="all" /> 全部
          </label>
          <label>
            <input type="radio" v-model="filters.evaluationStatus" value="notReviewed" /> 未批阅
          </label>
          <label>
            <input type="radio" v-model="filters.evaluationStatus" value="reviewed" /> 已批阅
          </label>
        </div>

        <!-- 提交状态（单选） -->
        <div class="filter-options">
          <p>提交状态：</p>
          <label>
            <input type="radio" v-model="filters.submissionStatus" value="all" /> 全部
          </label>
          <label>
            <input type="radio" v-model="filters.submissionStatus" value="notSubmitted" /> 未提交
          </label>
          <label>
            <input type="radio" v-model="filters.submissionStatus" value="onTime" /> 已提交
          </label>
          <label>
            <input type="radio" v-model="filters.submissionStatus" value="late" /> 补交
          </label>
        </div>

        <!-- 分班查看（单选，动态获取） -->
        <div class="filter-options">
          <p>分班查看：</p>
          <label>
            <input type="radio" v-model="filters.division" value="all" /> 全部
          </label>
          <label v-for="division in divisionList" :key="division.division_id">
            <input type="radio" v-model="filters.division" :value="division.division_id.toString()" /> {{ division.division_name }}
          </label>
        </div>
      </div>

      <!-- 作业概览区域 -->
      <div class="assignment-overview">
        <p style="margin-top: 0px;font-size:14px;color: #535353;">作业概览</p>
        <table class="overview-table" v-if="assignmentOverview">
          <thead style="color: #535353;">
            <tr>
              <th>学生人数</th>
              <th>未提交</th>
              <th>已提交</th>
              <th>补交</th>
              <th>未互评</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>{{ assignmentOverview.stu_cnt }}</td>
              <td>{{ assignmentOverview.unsubmitted }}</td>
              <td>{{ assignmentOverview.submit_cnt }}</td>
              <td>{{ assignmentOverview.remit_cnt }}</td>
              <td>{{ assignmentOverview.uneach_cnt }}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 学生作业情况表格 -->
      <div class="student-table-section">
        <div style="display: flex; justify-content: flex-end; align-items: center; margin-bottom: 20px;">
          <input
            type="text"
            v-model="searchTerm"
            placeholder="请输入姓名或学号搜索"
            class="search-input"
            @keyup.enter="searchStudent"
          />
          <button @click="searchStudent" class="search-button">搜索</button>
        </div>
        <table class="student-table">
          <thead>
            <tr>
              <th>序号</th>
              <th>姓名</th>
              <th>学号</th>
              <th>分班</th>
              <th>作品状态</th>
              <th>更新时间</th>
              <th>教师评分</th>
              <th>助教评分</th>
              <th>互评评分</th>
              <th>最终成绩</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
             <tr v-for="(student, index) in filteredPaginatedAssignments"
                :key="student.stu_hmwk_id || index"
                @click="handleRowClick(student)"
                style="cursor: pointer;"
                >
              <td style="font-size: 12px;">{{ index + 1 }}</td>
              <td>{{ student.username }}</td>
              <td style="font-size: 12px;">{{ student.stu_number || '--' }}</td>
              <td>{{ student.division_name || '--' }}</td>
              <td>
                <span
                  class="pill"
                  :class="{
                    'pill-green'  : student.submit_status === 1,   // 按时提交
                    'pill-orange' : student.submit_status === 2,   // 补交
                    'pill-gray'   : student.submit_status === 0    // 未提交
                  }"
                >
                  {{ getSubmitStatus(student.submit_status) }}
                </span>
              </td>
              <td style="font-size: 12px;">{{ student.update_time || '--' }}</td>
              <!-- 教师评分 -->
              <td>
                <span v-if="student.tech_grades && student.tech_grades.length">
                  <span style="font-size: 12px;" v-for="(grade, idx) in student.tech_grades" :key="grade.each_hmk_grade_id">
                    {{ grade.each_score }}{{ idx < student.tech_grades.length - 1 ? ' | ' : '' }}
                  </span>
                </span>
                <span v-else>--</span>
              </td>
               <!-- 助教评分 -->
              <td>
                <span v-if="student.admin_grades && student.admin_grades.length">
                  <span style="font-size: 12px;" v-for="(grade, idx) in student.admin_grades" :key="grade.each_hmk_grade_id">
                    {{ grade.each_score }}{{ idx < student.admin_grades.length - 1 ? ' | ' : '' }}
                  </span>
                </span>
                <span v-else>--</span>
              </td>
              <!-- 互评评分 -->
              <td>
                <span v-if="student.hmk_each_grades && student.hmk_each_grades.length">
                  <span style="font-size: 12px;" v-for="(grade, idx) in student.hmk_each_grades" :key="grade.each_hmk_grade_id">
                    {{ grade.each_score }}{{ idx < student.hmk_each_grades.length - 1 ? ' | ' : '' }}
                  </span>
                </span>
                <span v-else>--</span>
              </td>
              <!-- 最终成绩 -->
              <td style="font-size: 12px;color:green">{{ student.getscore !== null ? student.getscore : '--' }}</td>
              <td>
                <button class="review-button" @click.stop="reviewStudent(student)">批阅</button>
                <button class="adjust-button" @click.stop="openAdjustScoreModal(student)">调分</button>
              </td>
            </tr>
            <tr v-if="filteredPaginatedAssignments.length === 0">
              <td colspan="11" class="no-data">暂无数据</td>
            </tr>
          </tbody>
        </table>
        <!-- 分页组件 -->
        <PagiNation
          :currentPage="currentPage"
          :totalPages="totalPages"
          @page-change="handlePageChange"
        />
      </div>

      <!-- 调分弹窗 -->
      <div v-if="showAdjustScoreModal" class="modal-overlay">
        <div class="modal-content">
          <h3 style="text-align: center;">调分</h3>
          <p style="font-size:14px;color: #0B57D0;">规则：该学生的最终成绩将不会按照评分规则进行计算。</p>
          <div class="form-group" style="margin-bottom:20px">
            <label for="adjustedScore">新的成绩：</label>
            <input type="number" id="adjustedScore" v-model.number="adjustedScore" min="0" max="100" />
          </div>
          <div class="form-group" style="display: flex;">
            <label for="adjustReason" >调分理由：</label>
            <textarea id="adjustReason" v-model="adjustReason" rows="5" style="width: 70%;"></textarea>
          </div>
          <div class="modal-buttons" style="display:flex;justify-content: flex-end;">
            <button @click="submitAdjustedScore" style="margin-right:20px">提交</button>
            <button @click="closeAdjustScoreModal" style="margin-right:35px">取消</button>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { fetchAssignmentOverview, fetchStudentAssignments, fetchDivisionList, adjustStudentScore } from '@/services/api'; // 导入 adjustStudentScore
import PagiNation from '@/components/PagiNation.vue';
import AssignmentNavBar from '@/components/AssignmentNavBar.vue'; // 引入导航栏组件
import { useRouter } from 'vue-router'; // Import useRouter

export default {
  name: 'AssignmentList',
  components: { PagiNation, AssignmentNavBar },
  props: {
    homeworkId: {
      type: [String, Number],
      required: true,
    },
    semesterId: {
      type: [String, Number],
      required: true,
    },
  },
  setup(props) {
    const router = useRouter();
    const assignmentOverview = ref(null);
    const studentAssignments = ref([]);
    const divisionList = ref([]);
    const currentPage = ref(1);
    const itemsPerPage = ref(10);
    const searchTerm = ref('');
    const errorMessage = ref('');

    // 调分弹窗相关状态
    const showAdjustScoreModal = ref(false);
    const adjustedScore = ref(null);
    const adjustReason = ref('');
    const selectedStudent = ref(null);

    // 处理批阅按钮点击事件
    const reviewStudent = (student) => {
      if (!student.stu_hmwk_id) {
        ElMessage.warning('该学生未提交作业，无法批阅。');
        return;
      }
      router.push({
        name: 'StudentAssignmentReview',
        params: {
          homeworkId: props.homeworkId,
          stuHmwkId: student.stu_hmwk_id,
        },
      });
    };

    // 处理行点击事件
    const handleRowClick = (student) => {
      if (!student.stu_hmwk_id) {
        return;
      }
      reviewStudent(student);
    };

    // 初始化 filters 对象，默认选择 'all'
    const filters = ref({
      evaluationStatus: 'all', // 单选
      submissionStatus: 'all', // 单选
      division: 'all', // 单选
    });

    // 获取作业概览（独立于过滤条件）
    const loadAssignmentOverview = async () => {
      try {
        const overviewResponse = await fetchAssignmentOverview(props.homeworkId);
        if (overviewResponse.data.status === 1) {
          assignmentOverview.value = overviewResponse.data.data;
        } else {
          errorMessage.value = `获取作业概览失败: ${overviewResponse.data.msg}`;
        }
      } catch (error) {
        errorMessage.value = '加载作业概览失败，请稍后重试。';
      }
    };

    // 获取分班列表
    const loadDivisionList = async () => {
      if (props.semesterId === null || props.semesterId === undefined) {
        errorMessage.value = '无法获取分班列表，因为 semesterId 未定义。';
        return;
      }
      try {
        const response = await fetchDivisionList(String(props.semesterId));
        if (response.data.status === 1) {
          divisionList.value = response.data.data;
        } else {
          errorMessage.value = `获取分班列表失败: ${response.data.msg}`;
        }
      } catch (error) {
        errorMessage.value = '加载分班列表失败，请稍后重试。';
      }
    };

    // 获取学生作业列表（基于过滤条件）
    const loadStudentAssignments = async () => {
      try {
        // 准备过滤参数，确保所有参数都被发送
        const filterParams = {
          is_grade:
            filters.value.evaluationStatus === 'all'
              ? null
              : filters.value.evaluationStatus === 'notReviewed'
              ? 0
              : 1,
          submit_status:
            filters.value.submissionStatus === 'all'
              ? null
              : filters.value.submissionStatus === 'notSubmitted'
              ? 0
              : filters.value.submissionStatus === 'onTime'
              ? 1
              : 2,
          division_id:
            filters.value.division === 'all' ? null : Number(filters.value.division),
        };

        // 获取学生作业列表
        const studentResponse = await fetchStudentAssignments(String(props.homeworkId), filterParams);
        if (studentResponse.data.status === 1) {
          studentAssignments.value = studentResponse.data.data;
          errorMessage.value = ''; // 清除错误信息
        } else {
          errorMessage.value = `获取学生作业列表失败: ${studentResponse.data.msg}`;
        }

        // 重置当前页
        currentPage.value = 1;
      } catch (error) {
        errorMessage.value = '加载学生作业列表失败，请稍后重试。';
      }
    };

    // 获取提交状态文本
    const getSubmitStatus = (status) => {
      switch (status) {
        case 0:
          return '未提交';
        case 1:
          return '已提交';
        case 2:
          return '补交';
        default:
          return '--';
      }
    };

    // 处理分页变化
    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
    };

    // 打开调分弹窗
    const openAdjustScoreModal = (student) => {
      if (!student.id) { // 确保学生数据中有 'id'
        ElMessage.warning('学生ID不存在，无法调分。');
        return;
      }
      selectedStudent.value = student;
      adjustedScore.value = student.getscore !== null ? student.getscore : 0; // 默认设置为当前成绩
      adjustReason.value = ''; // 清空调分理由
      showAdjustScoreModal.value = true;
    };

    // 关闭调分弹窗
    const closeAdjustScoreModal = () => {
      showAdjustScoreModal.value = false;
      adjustedScore.value = null;
      adjustReason.value = '';
      selectedStudent.value = null;
    };

    // 提交调分
    const submitAdjustedScore = async () => {
      if (adjustedScore.value === null || adjustReason.value.trim() === '') {
        ElMessage.warning('请填写所有字段后再提交。');
        return;
      }

      const data = {
        stu_hmwk_id: selectedStudent.value.stu_hmwk_id,
        getscore: adjustedScore.value,
        why_ruleout: adjustReason.value,
        id: selectedStudent.value.id, // 被调分用户的ID
        homework_id: Number(props.homeworkId),
      };

      try {
        const response = await adjustStudentScore(data);
        if (response.data.status === 1) {
          ElMessage.success('调分成功！');
          closeAdjustScoreModal();
          await loadStudentAssignments(); // 重新加载学生作业列表以反映更改
        } else {
          ElMessage.error(`调分失败: ${response.data.msg}`);
        }
      } catch (error) {
        console.error('调分请求失败:', error);
        ElMessage.error('调分请求失败，请稍后重试。');
      }
    };

    // 搜索功能（仅在前端实现）
    const searchStudent = () => {
      // 触发计算属性的更新
      // 这里不需要具体实现，因为计算属性会自动响应 searchTerm 的变化
    };

    // 监视过滤条件变化，重新加载学生作业数据
    watch(
      filters,
      () => {
        loadStudentAssignments();
      },
      { deep: true }
    );

    // 监视搜索条件变化，重新过滤学生作业数据
    const filteredPaginatedAssignments = computed(() => {
      let filtered = studentAssignments.value;

      if (searchTerm.value.trim() !== '') {
        const term = searchTerm.value.trim().toLowerCase();
        filtered = filtered.filter(
          (student) =>
            (student.username && student.username.toLowerCase().includes(term)) ||
            (student.stu_number && student.stu_number.includes(term))
        );
      }

      const start = (currentPage.value - 1) * itemsPerPage.value;
      const end = start + itemsPerPage.value;
      return filtered.slice(start, end);
    });

    onMounted(async () => {
      await loadAssignmentOverview(); // 独立获取作业概览
      await loadDivisionList();
      await loadStudentAssignments(); // 获取学生作业列表
    });

    // 总页数（基于过滤后的数据）
    const totalPages = computed(() => {
      const totalItems =
        searchTerm.value.trim() !== ''
          ? studentAssignments.value.filter(
              (student) =>
                (student.username && student.username.toLowerCase().includes(searchTerm.value.trim().toLowerCase())) ||
                (student.stu_number && student.stu_number.includes(searchTerm.value.trim()))
            ).length
          : studentAssignments.value.length;
      return Math.ceil(totalItems / itemsPerPage.value);
    });

    return {
      assignmentOverview,
      studentAssignments,
      divisionList,
      getSubmitStatus,
      currentPage,
      totalPages,
      handlePageChange,
      searchTerm,
      filters,
      filteredPaginatedAssignments,
      searchStudent,
      errorMessage,
      reviewStudent,
      handleRowClick,
      // 调分弹窗相关
      showAdjustScoreModal,
      adjustedScore,
      adjustReason,
      openAdjustScoreModal,
      closeAdjustScoreModal,
      submitAdjustedScore,
    };
  },
};
</script>



<style scoped>
.pill  {
  display:inline-block;
  padding:3px 14px;
  border-radius:999px;
  font-size:12px;
  line-height:18px;
  min-width:40px;
  text-align:center;
  background:transparent;  
}

/* 按时提交 – 绿色 */
.pill-green  {
  border:1px solid #7bd68c;  
  color:#29ad48;             
}

/* 补交 – 橙色 */
.pill-orange {
  border:1px solid #ffc684; 
  color:orange;
}

/* 未提交 – 灰色 */
.pill-gray   {
  border:1px solid rgba(255, 0, 0, 0.29);
;
  color:rgba(255, 0, 0, 0.622);
}

.container {
  width: 100vw;
  background: #F9F9F9;
  min-height: 100vh;
  padding: 20px;
  padding-top: 0px;
}

.navbar {
  display: flex;
  gap: 20px;
  background-color: #ffffff;
  padding: 15px 30px;
}

.nav-link {
  text-decoration: none;
  color: #244382;
  font-size: 18px;
  font-weight: bold;
}

.nav-link.router-link-exact-active {
  color: #1e3661;
  border-bottom: 2px solid #1e3661;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding-left: 30px;
  font-size: 14px;
  border: 1px solid #f5c6cb;
}

.filter-section {
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  padding: 0px 30px;
  color: #535353;
  padding-top: 20px;
}

.filter-options {
  display: flex;
  gap: 15px;
  align-items: center;
  margin-bottom: 30px;
  font-size: 14px;
}

.filter-options p {
  margin: 0;
}

.assignment-overview {
  background-color: #ffffff;
  padding: 0px 30px;
}

.overview-table {
  width: 100%;
  border-collapse: collapse;
}

.overview-table th,
.overview-table td {
  border-block-end: 1px solid rgba(221, 221, 221, 0.453);
  padding: 12px;
  text-align: center;
  background-color: #F6F7F9;
  font-size: 14px;
  font-weight: normal;
}
.overview-table td {
  background-color: #FFFFFF;
  color: #4a669d;
}

.student-table-section {
  background-color: #ffffff;
  padding: 20px 30px;
  margin-bottom: 20px;
}

.search-input {
  padding: 8px 12px;
  margin-right: 10px;
  width: 250px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.search-button {
  padding: 8px 16px;
  background-color: #2f57a7;
  color: white;
  border: none;
  cursor: pointer;
  border-radius: 4px;
}
.search-button:hover {
  background-color: #2a4d8f;
}

.student-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

/* 表头背景色 */
.student-table th {
  background-color: #F6F7F9; /* 与 overview-table th 相同 */
  font-size: 14px;
  font-weight: normal;
  border-block-end: 1px solid rgba(221, 221, 221, 0.453);
  padding: 12px;
  text-align: center;
  color: #535353;
}

.student-table tr:hover {
  background-color: #f9f9f9; /* 浅灰色 */
}

.student-table tr {
  background-color: #FFFFFF; /* 白色 */
}

/* 表体单元格文字颜色 */
.student-table td {
  color: #696969;
  padding: 12px;
  text-align: center;
  font-size: 14px;
  border-block-end: 1px solid rgba(221, 221, 221, 0.453);
}

/* 操作按钮样式 */
.review-button {
  background-color: #1e90ff; /* 蓝色 */
  color: white;
  border: none;
  padding: 5px 10px;
  margin-right: 5px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.review-button:hover {
  background-color: #1c86ee;
}

.adjust-button {
  background-color: #32cd32; /* 绿色 */
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.adjust-button:hover {
  background-color: #2eb82e;
}

/* 初始状态下按钮透明且不可见，但仍占据空间 */
.review-button,
.adjust-button {
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s ease, visibility 0s linear 0.3s;
}

/* 当鼠标悬停在行上时，显示按钮 */
.student-table tbody tr:hover .review-button,
.student-table tbody tr:hover .adjust-button {
  opacity: 1;
  visibility: visible;
  transition: opacity 0.3s ease;
  
}

/* 固定 "操作" 列的宽度，防止布局变化 */
.student-table th:last-child,
.student-table td:last-child {
  width: 120px; /* 根据按钮的实际宽度调整此值 */
  text-align: center; /* 确保按钮居中 */
}

/* 可选：调整按钮的样式，使其在出现时更美观 */
.review-button,
.adjust-button {
  margin: 0 2px;
}

.no-data {
  text-align: center;
  padding: 20px;
  font-size: 16px;
}

button {
  cursor: pointer;
}

/* 调分弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: #fff;
  padding: 30px;
  border-radius: 5px;
  width: 400px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.modal-content h3 {
  margin-top: 0;
}

.modal-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.modal-buttons button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.modal-buttons button:first-child {
  background-color: #244382;
  color: #fff;
}

.modal-buttons button:last-child {
  background-color: #ccc;
  color: #333;
}
</style>

